<template>
    <div class="frame">
        <div class="left">
            <el-card shadow="always" class="card">
                <h2> 云枫聊天室 </h2>
                <div v-for="item in receiveMsgList" style="width: 480px; margin-bottom: 10px;">
                    {{ item.type === 'ENTER' ? `${item.msg} ${item.userName}` : `${item.userName}: ${item.msg} ` }}
                </div>
            </el-card>
        </div>

        <div class="right">
            <el-form ref="ruleFormRef" label-width="80" inline class="top">
                <el-form-item label="你的昵称">
                    <el-input v-model="userName" :disabled="isConnect" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="isConnect" @click="getWebSocket()">
                        加入聊天室
                    </el-button>
                    <el-button @click="exit()">退出</el-button>
                </el-form-item>
            </el-form>
            <el-form ref="ruleFormRef" style="width: 480px;" label-width="80" class="bottom">
                <el-form-item label="发送信息">
                    <el-input v-model="msg" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="sendInfo()">
                        发送
                    </el-button>
                    <el-button @click="clearInfo()">清屏</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import useWebSocket from './useWebSocket';
import { reactive } from 'vue';
import dayjs from 'dayjs';

interface ChatMsg {
    userName: string,
    type: string,
    msg: string,
    onlineCount: number
}
const id = dayjs().format('YYYYMMDDHHmmss');
const msg = ref(''), userName = ref('test' + id), isConnect = ref(false)
const sendInfo = () => {
    sendMsg(msg.value)
}
const clearInfo = () => {
    receiveMsgList.splice(0);
}
const receiveMsgList = reactive<ChatMsg[]>([])

const { connectWS, closeWs, sendMsg } = useWebSocket();

const getWebSocket = () => {
    const ws = connectWS(userName.value);
    ws.onmessage = (event => {
        const data = JSON.parse(event.data);
        receiveMsgList.push(data);
        isConnect.value = true;
    })
}

const exit = () => {
    closeWs();
    isConnect.value = false;
}
getWebSocket();


</script>

<style scoped lang="scss">
.frame {
    height: 100%;
    display: flex;
    // flex-direction: column;
    // align-items: center;

    .left {
        flex: 1;
        padding: 50px;

        .card {
            height: 100%;

            h2 {
                font-weight: bold;
                line-height: 40px;
            }
        }
    }

    .right {
        flex: 1;
        padding: 50px;
    }
}
</style>